package com.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reggie.common.R;
import com.reggie.entity.User;
import com.reggie.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

//    登录判断逻辑
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session) {
        log.info(map.toString());
//        获取手机号
        String phone = map.get("phone").toString();
//        获取验证码
        String code = map.get("code").toString();
//        把验证码与session里的进行判断
//        如果验证码比对正确
//        查看一下该手机号数据库是否有 如果没有就自动生成
        LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userLambdaQueryWrapper.eq(User::getPhone, phone);//比对
        User user = userService.getOne(userLambdaQueryWrapper);//判断是否有数据
        if (user == null) {
            user= new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);//添加是用save  修改是update
        }
//        由于前面多线程校验的时候判断了session里的id是否存在  作为唯一标识
        session.setAttribute("user",user.getId());
//        return R.success("登录成功");
        return R.success(user);
    }

}
